package com.aote.gradleproject.util;


import com.aote.gradleproject.pojo.AlipayParameterForBangDao;

import javax.net.ssl.*;
import java.net.ServerSocket;
import java.security.KeyStore;


/**
 * 创建监听器
 * @author 张琪
 * @date 2021/7/16 16:47
 */
public final class HttpSslSocket {

	/**
	 * 生成一个 监听制定端口的 ServerSocket
	 * @param config
	 * @return
	 */
	public static ServerSocket createSslServerSocket(AlipayParameterForBangDao config) {
		try {
			int port = config.getPort();

			// 服务端自身私钥路劲、私钥密码(这里存储的是密钥存储路径)
			String privateKey = config.getPrivateKey();
			String privateKeyPassword = config.getPrivateKeyPassword();

			// 信任的证书列表,即客户端证书路劲、证书密码
			String trustKey = config.getTrustKey();
			String trustKeyPassword = config.getTrustKeyPassword();

			SSLContext ctx = SSLContext.getInstance("SSL");

			KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
			TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");

			KeyStore ks = KeyStore.getInstance("JKS");
			KeyStore tks = KeyStore.getInstance("JKS");

//			  使用getResourceAsStream() 获取打包后的jar文件中的密钥文件字节流
			ks.load(Resource.class.getResourceAsStream(privateKey), privateKeyPassword.toCharArray());
			tks.load(Resource.class.getResourceAsStream(trustKey), trustKeyPassword.toCharArray());

			kmf.init(ks, privateKeyPassword.toCharArray());
			tmf.init(tks);

			ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

			SSLServerSocket serverSocket = (SSLServerSocket) ctx
					.getServerSocketFactory().createServerSocket(port);
			serverSocket.setNeedClientAuth(true);
			return serverSocket;
		} catch (Exception e) {
			System.err.println("创建SSL双向认证链接失败!");
			e.printStackTrace();
		}
		return null;
	}
}
